Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Is it okay to declare the db instance as a global variable for accessible at all the time , without need to use "require" statement in node js

I am a beginner in "node js" I am developing an program and I want to use the database model in all For example (something like "wpdb") WordPress Is the best way to create it as a global variable, or to use the require statement as needed?

Please help me get the best answer. Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No, this is not the best way to handle a db connection. You only want the db open and around for as long as necessary and no longer. Usually this means opening the db connection at the place in your code that can know how long to keep it open and then close the connection after using it.

If you are simply referring to the configuration for opening a DB connection, then you could define that configuration object at application start and then pass it as a parameter to your db instantiation code.

import myUserDbCode from '../myUserDbFile';
import myUserMessagesCode from '../myUserMsgsDbFile';

const dbConfig = {
  dbname: 'myFancyDb',
  serverName: 'myDbServerName',
  connectionTimeout: 60
}

(async () => {

  const userList = await myUserDbCode(dbConfig)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  const myUser = userList[42];

  const userMessages = await myUserMessagesCode(dbConfig, myUser)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  console.log(userMessages);
})();

I recommend following some DB tutorials that show how to build a complete application to see some patterns about how to handle passing configuration options to code and how to manage DB connections.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!